//
//  AppDelegate.m
//  HeadIndustry
//
//  Created by jun on 2017/8/24.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#import <WXApi.h>
//#import <WXApiManager.h>
@interface AppDelegate ()<CLLocationManagerDelegate,WXApiDelegate>

@property (nonatomic,strong) CLLocationManager *manager;


@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 读取缓存数据
    [GLOBALDATA restoreData];
    
    [self setUpLocation];
    
    [self setConfigWeiXin];
    
    return YES;
}

- (void)setConfigWeiXin
{
    
    [WXApi registerApp:WXAPIStr];
    
    //向微信注册支持的文件类型
    UInt64 typeFlag = MMAPP_SUPPORT_TEXT | MMAPP_SUPPORT_PICTURE | MMAPP_SUPPORT_LOCATION | MMAPP_SUPPORT_VIDEO |MMAPP_SUPPORT_AUDIO | MMAPP_SUPPORT_WEBPAGE | MMAPP_SUPPORT_DOC | MMAPP_SUPPORT_DOCX | MMAPP_SUPPORT_PPT | MMAPP_SUPPORT_PPTX | MMAPP_SUPPORT_XLS | MMAPP_SUPPORT_XLSX | MMAPP_SUPPORT_PDF;
    
    [WXApi registerAppSupportContentFlag:typeFlag];
}

- (void)setUpLocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        
        _manager = [[CLLocationManager alloc] init];
        _manager.delegate = self;
        _manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        _manager.distanceFilter  = kCLDistanceFilterNone;
        [_manager startUpdatingLocation];  // 开始定位
//        [_manager startUpdatingHeading];  // 开始更新方向
        
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"无法进行定位", comment:@"无法进行定位") message:NSLocalizedString(@"请检查您的设备是否开启定位功能", comment:@"请检查您的设备是否开启定位功能") delegate:self cancelButtonTitle:NSLocalizedString(@"确定",comment:@"确定") otherButtonTitles:nil, nil];
        [alert show];
    }
    // 实例化对象
    _manager = [[CLLocationManager alloc] init];
    
    _manager.delegate = self;
    
    // 请求授权，记得修改的infoplist，NSLocationAlwaysUsageDescription（描述）
    [_manager requestWhenInUseAuthorization];
    
//    [_manager stopUpdatingLocation];


    [_manager startUpdatingLocation];
    
}

#pragma mark - 代理方法，当授权改变时调用
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    
    // 获取授权后，通过
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
        
        //开始定位(具体位置要通过代理获得)
        [_manager startUpdatingLocation];
        
        //设置精确度
        _manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
        
        //设置过滤距离
        _manager.distanceFilter = 1000;
        
        //开始定位方向
//        [_manager startUpdatingHeading];
    }
    
    
}

//#pragma mark - 方向
//- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
//    
//    //输出方向
//    
//    //地理方向
//    NSLog(@"true = %f ",newHeading.trueHeading);
//    
//    // 磁极方向
//    NSLog(@"mag = %f",newHeading.magneticHeading);
//    
//    
//    
//}

#pragma mark - 定位代理
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    //    NSLog(@"%@",locations);
    
    //获取当前位置
    CLLocation *location = manager.location;
    //获取坐标
//    CLLocationCoordinate2D corrdinate = location.coordinate;
    
    //打印地址
//    NSLog(@"latitude = %f longtude = %f",corrdinate.latitude,corrdinate.longitude);
    
    // 地址的编码通过经纬度得到具体的地址
    CLGeocoder *gecoder = [[CLGeocoder alloc] init];
    
    [gecoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        CLPlacemark *placemark = [placemarks firstObject];

        if (placemark != nil) {
            NSMutableString *addressStr = [NSMutableString string];
            [addressStr appendString:placemark.administrativeArea];
            [addressStr appendString:placemark.locality];
            [addressStr appendString:placemark.subLocality];
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:placemark.locality forKey:@"cityName"];
            [dic setValue:addressStr forKey:@"cityLocation"];
            [dic setValue:@(placemark.location.coordinate.latitude) forKey:@"cityLocationLat"];
            [dic setValue:@(placemark.location.coordinate.longitude) forKey:@"cityLocationLng"];
            
            
            [UserDefaultsDelegate setObject:dic forKey:UserLocationCity];
            [UserDefaultsDelegate synchronize];
        }
//        NSLog(@"======%@",placemark.administrativeArea);
//        NSLog(@"======%@",placemark.locality);
//        NSLog(@"======%@",placemark.subLocality);

        
        //打印地址
//        NSLog(@"地址====%@",placemark.locality);
    }];
    
//    // 通过具体地址去获得经纬度
//    CLGeocoder *coder = [[CLGeocoder alloc] init];
//    
//    [coder geocodeAddressString:@"天河城" completionHandler:^(NSArray *placemarks, NSError *error) {
//        
//        
//        
//        NSLog(@"_________________________反编码");
//        
//        CLPlacemark *placeMark = [placemarks firstObject];
//        
//        
//        
//        NSLog(@"%@ lati = %f long = %f",placeMark.name,placeMark.location.coordinate.latitude,placeMark.location.coordinate.longitude);
//        
//        
//    }];
    
    
    //停止定位
    [_manager stopUpdatingLocation];
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:self];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary*)options{
    return [WXApi handleOpenURL:url delegate:self];
}

//微信代理方法
- (void)onResp:(BaseResp *)resp
{
    
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if(aresp.errCode== 0 && [aresp.state isEqualToString:WXAuthStateLogin])
    {
        NSString *code = aresp.code;
        
        NSString *url = @"WeChart/GetOpenId";
        [JNetManager getUserWXInfoRequestUrl:url code:code success:^(id response) {
            if (response) {
                
                JUserInfoModel *infoModel = [JUserInfoModel new];
                [infoModel setValuesForKeysWithDictionary:response];
                [GLOBALDATA setUserInfoModel:infoModel];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"wxlogin" object:nil];
                
                
            }
        } failure:^(NSString *err) {
            [SVProgressHUD showErrorWithStatus:err];
        }];
        
    }
    else if (aresp.errCode== 0 && [aresp.state isEqualToString:WXAuthStateRegist]) {
        NSString *code = aresp.code;
        
        NSString *url = @"WeChart/GetOpenId";
        [JNetManager getUserWXInfoRequestUrl:url code:code success:^(id response) {
            if (response) {
                
                JUserInfoModel *infoModel = [JUserInfoModel new];
                [infoModel setValuesForKeysWithDictionary:response];
                [GLOBALDATA setUserInfoModel:infoModel];
                
                if (infoModel.Tel.length > 0) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"zhucelogin" object:@1];
                }
                else
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"zhucelogin" object:@0];
                }
                
            }
        } failure:^(NSString *err) {
            [SVProgressHUD showErrorWithStatus:err];
        }];
    }
}


////通过code获取access_token，openid，unionid
//- (void)getWeiXinOpenId:(NSString *)code{
//    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAPIStr,WXAppSerect,code];
//    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        NSURL *zoneUrl = [NSURL URLWithString:url];
//        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
//        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (data){
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
////                NSString *openID = dic[@"openid"];
////                NSString *unionid = dic[@"unionid"];
//                
//                NSDictionary *refreshDict = [NSDictionary dictionaryWithDictionary:dic];
//                NSString *reAccessToken = [refreshDict objectForKey:WX_ACCESS_TOKEN];
//                // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
//                if (reAccessToken == nil) {
//                    // 更新access_token、refresh_token、open_id
//                    [UserDefaultsDelegate setObject:reAccessToken forKey:WX_ACCESS_TOKEN];
//                    [UserDefaultsDelegate setObject:[refreshDict objectForKey:WX_OPEN_ID] forKey:WX_OPEN_ID];
//                    [UserDefaultsDelegate setObject:[refreshDict objectForKey:WX_REFRESH_TOKEN] forKey:WX_REFRESH_TOKEN];
//                    [UserDefaultsDelegate synchronize];
//
//                }
//            }
//        });
//    });
//    
//}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [GLOBALDATA saveData];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    [GLOBALDATA saveData];
}


@end
